package com.imooc.hadoop.mapreduce.multipleOutput;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

import java.io.IOException;

/**
 * @program: hadoop_db
 * @description: MultipleOutReducer
 * @author: zengchen
 * @create: 2021-04-01 20:39
 **/
public class MultipleOutReducer extends Reducer<Text, LongWritable, Text, NullWritable> {

    private MultipleOutputs<Text, NullWritable> multipleOutputs;
    private Configuration configuration;

    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        long count = 0;
        for (LongWritable value : values) {
            count += value.get();
        }
        Configuration configuration = context.getConfiguration();
        if ("hello".equals(key.toString())) {
            multipleOutputs.write(new Text(key.toString() + "," + count),
                    NullWritable.get(),
                    configuration.get("path1", "type1/type1"));
        } else {
            multipleOutputs.write(new Text(key.toString() + "," + count),
                    NullWritable.get(),
                    configuration.get("path2", "type2/type1"));
        }

    }

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        multipleOutputs = new MultipleOutputs<Text, NullWritable>(context);
        configuration = context.getConfiguration();
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        multipleOutputs.close();
    }
}
